﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Web;
using System.Web.Mvc;
using System.Security.Cryptography;
using System.Net;
using System.IO;
using Kunlun.Models;
using System.Linq;
namespace Kunlun.BusinessLogic
{
    public class AliPay
    {

        private string GetMD5(string s, string _input_charset)
        {

            /// <summary>
            /// 与ASP兼容的MD5加密算法
            /// </summary>

            MD5 md5 = new MD5CryptoServiceProvider();
            byte[] t = md5.ComputeHash(Encoding.GetEncoding(_input_charset).GetBytes(s));
            StringBuilder sb = new StringBuilder(32);
            for (int i = 0; i < t.Length; i++)
            {
                sb.Append(t[i].ToString("x").PadLeft(2, '0'));
                
            }
            return sb.ToString();
        }

        private string[] BubbleSort(string[] r)
        {
            /// <summary>
            /// 冒泡排序法
            /// </summary>

            int i, j; //交换标志 
            string temp;

            bool exchange;

            for (i = 0; i < r.Length; i++) //最多做R.Length-1趟排序 
            {
                exchange = false; //本趟排序开始前，交换标志应为假

                for (j = r.Length - 2; j >= i; j--)
                {
                    if (System.String.CompareOrdinal(r[j + 1], r[j]) < 0)　//交换条件
                    {
                        temp = r[j + 1];
                        r[j + 1] = r[j];
                        r[j] = temp;

                        exchange = true; //发生了交换，故将交换标志置为真 
                    }
                }

                if (!exchange) //本趟排序未发生交换，提前终止算法 
                {
                    break;
                }

            }
            return r;
        }

        private string CreatUrl(
            string gateway,
            string service,
            string partner,
            string sign_type,
            string out_trade_no,
            string subject,
            string body,
            string payment_type,
            string total_fee,
            string show_url,
            string seller_email,
            string key,
            string return_url,
            string _input_charset,
            string notify_url,
            string logistics_type,
            string logistics_fee,
            string logistics_payment,
            string logistics_type_1,
            string logistics_fee_1,
            string logistics_payment_1,
            string quantity,
            string paymethd,
            string buyer_email
            )
        {
            /// <summary>
            /// created by sunzhizhi 2006.5.21,sunzhizhi@msn.com。
            /// </summary>
            int i;

            //构造数组；
            string[] Oristr ={ 
                "service="+service, 
                "partner=" + partner, 
                "subject=" + subject, 
                "body=" + body, 
                "out_trade_no=" + out_trade_no, 
                "price=" + total_fee, 
                "show_url=" + show_url,  
                "payment_type=" + payment_type, 
                "seller_email=" + seller_email, 
                "notify_url=" + notify_url,
                "_input_charset="+_input_charset,          
                "return_url=" + return_url,
                "quantity="+quantity,
                "logistics_type="+logistics_type,
                "logistics_fee="+logistics_fee ,
                "logistics_payment="+logistics_payment,
	            "logistics_type_1="+logistics_type_1,
                "logistics_fee_1="+logistics_fee_1,
                "logistics_payment_1="+logistics_payment_1,
                "paymethd="+paymethd,
                "buyer_email="+buyer_email
                };

            //进行排序；
            string[] Sortedstr = BubbleSort(Oristr);


            //构造待md5摘要字符串 ；

            StringBuilder prestr = new StringBuilder();

            for (i = 0; i < Sortedstr.Length; i++)
            {
                if (i == Sortedstr.Length - 1)
                {
                    prestr.Append(Sortedstr[i]);

                }
                else
                {

                    prestr.Append(Sortedstr[i] + "&");
                }

            }

            prestr.Append(key);

            //生成Md5摘要；
            string sign = GetMD5(prestr.ToString(), _input_charset);

            //构造支付Url；
            char[] delimiterChars = { '=' };
            StringBuilder parameter = new StringBuilder();
            parameter.Append(gateway);
            for (i = 0; i < Sortedstr.Length; i++)
            {

                parameter.Append(Sortedstr[i].Split(delimiterChars)[0] + "=" + HttpUtility.UrlEncode(Sortedstr[i].Split(delimiterChars)[1]) + "&");
            }

            parameter.Append("sign=" + sign + "&sign_type=" + sign_type);


            //返回支付Url；
            return parameter.ToString();

        }

        //获取远程服务器ATN结果
        private  String Get_Http(String a_strUrl, int timeout)
        {
            string strResult;
            try
            {

                HttpWebRequest myReq = (HttpWebRequest)HttpWebRequest.Create(a_strUrl);
                myReq.Timeout = timeout;
                HttpWebResponse HttpWResp = (HttpWebResponse)myReq.GetResponse();
                Stream myStream = HttpWResp.GetResponseStream();
                StreamReader sr = new StreamReader(myStream, Encoding.Default);
                StringBuilder strBuilder = new StringBuilder();
                while (-1 != sr.Peek())
                {
                    strBuilder.Append(sr.ReadLine());
                }

                strResult = strBuilder.ToString();
            }
            catch (Exception exp)
            {

                strResult = "错误：" + exp.Message;
            }

            return strResult;
        }

        public string ToURL(string orderid, string productname, string price,  string useremail, string host)
        {
        #region  taobao支付
        KunLunEntities newKunLunEntities = new KunLunEntities();
        Paymethod pay=newKunLunEntities.Paymethod.FirstOrDefault(p=>p.Name=="支付宝");
        string out_trade_no = orderid + "_" + new Random().Next(9999999);//交易编号
        //业务参数赋值；
        string gateway = "https://www.alipay.com/cooperate/gateway.do?";	//'支付接口
        
        string sign_type = "MD5";
        string subject = "订单号|" + orderid;	//subject		商品名称
        string body = productname;		//body			商品描述    
        string payment_type = "1";
        string service = pay.Service;//直接支付接口 create_direct_pay_by_user
        string partner = pay.Partner;		//partner		合作伙伴ID			保留字段

        string quantity = "1";
        string show_url = host;
        string seller_email = pay.SellerEmail;             //卖家账号
        string key = pay.ClientKey;              //partner账户的支付宝安全校验码
        string return_url = host + pay.Returnurl;                   //服务器通知返回接口
        string notify_url = host + pay.NotifyUrl;                //服务器通知返回接口
        string _input_charset = "utf-8";
        string logistics_type = "EMS";
        string logistics_fee = "0.01";
        string logistics_payment = "BUYER_PAY";
        string logistics_type_1 = "EXPRESS";
        string logistics_fee_1 = "0.01";
        string logistics_payment_1 = "BUYER_PAY";
        string buyer_email = useremail;
        string paymethd = "directPay";
        AliPay ap = new AliPay();
        string aliay_url = ap.CreatUrl(
            gateway,
            service,
            partner,
            sign_type,
            out_trade_no,
            subject,
            body,
            payment_type,
            price,
            show_url,
            seller_email,
            key,
            return_url,
            _input_charset,
            notify_url,
            logistics_type,
            logistics_fee,
            logistics_payment,
            logistics_type_1,
            logistics_fee_1,
            logistics_payment_1,
            quantity,
            paymethd,
            buyer_email
            );

        return aliay_url;
        #endregion    
        }
        public string GetURL(FormCollection collection)
        {
        AliPay ap = new AliPay();
        Paymethod pay = new KunLunEntities().Paymethod.FirstOrDefault(p => p.Name == "支付宝");

        string alipayNotifyURL = "http://notify.alipay.com/trade/notify_query.do?";
        string key = pay.ClientKey;// "hy6ktsdphhb1bns67i6kweduqvtnc62i"; //partner 的对应交易安全校验码（必须填写）
        string _input_charset = "utf-8";
        string partner = pay.Partner; //"2088002047025824"; 		//partner合作伙伴id（必须填写）
        string responseTxt = null;
        string mysign = null;
        string sign = null;
        string subject = null;
        string OrderFormID = null;
        string total_fee = null;
        alipayNotifyURL = alipayNotifyURL + "service=notify_verify" + "&partner=" + partner + "&notify_id=" + collection["notify_id"];



        //获取支付宝ATN返回结果，true是正确的订单信息，false 是无效的
        responseTxt = ap.Get_Http(alipayNotifyURL, 120000);
        int i;
        
        String[] requestarr = collection.AllKeys;

        string[] Sortedstr = ap.BubbleSort(requestarr);

       

        StringBuilder prestr = new StringBuilder();

        for (i = 0; i < Sortedstr.Length; i++)
            {
            if (collection[Sortedstr[i]] != "" && Sortedstr[i] != "sign" && Sortedstr[i] != "sign_type")
                {
                if (i == Sortedstr.Length - 1)
                    {
                    prestr.Append(Sortedstr[i] + "=" + collection[Sortedstr[i]]);
                    }
                else
                    {
                    prestr.Append(Sortedstr[i] + "=" + collection[Sortedstr[i]] + "&");

                    }
                }


            }

        prestr.Append(key);

        // 生成Md5摘要；
        mysign = ap.GetMD5(prestr.ToString(), _input_charset);
        sign = collection["sign"];
        
        if (mysign == sign && responseTxt == "true")
            {

            return "success";

            }
        else
        { return "fail"; }
            
         }
    }
}
